var express = require("express");
var router = express.Router();
var file = require("../read");
/* GET home page. */
// 中间件：加载文件数据
async function loadFileData(req, res, next) {
  try {
    req.data = await file.getFileData("../data621.json");
    if (!req.data.car) {
      return res.json({
        code: 200,
        message: "success",
        data: [],
      });
    }
    next();
  } catch (error) {
    next(error);
  }
}
// 中间件：验证添加车辆请求
function validateAddCarRequest(req, res, next) {
  const { username, pwe, carColor } = req.body;
  if (!username || !pwe || !carColor) {
    return res.status(400).json({ code: 400, message: "请求参数不能为空" });
  }
  next();
}
// 中间件：删除，验证修改和搜索车辆请求
function validateCarId(req, res, next) {
  const id = req.params.id;
  if (!id || isNaN(id) || id <= 0) {
    return res.status(400).json({ code: 400, message: "请输入正确的id" });
  }
  next();
}
// 获取车辆信息
router.get("/get/car", loadFileData, function (req, res) {
  // 判断数据是否为空
  return res.json({
    code: 200,
    message: "success",
    data: req.data.car,
  });
});
// 添加
router.post("/post/car", validateAddCarRequest, async (req, res) => {
  let data = await file.getFileData("../data621.json");
  // 判断数据是否为空
  if (!data.car) {
    data.car = [];
  }
  // 为添加的数据增加一个id属性
  let id =
    data.car.length > 0 ? Math.max(...data.car.map((car) => car.id)) + 1 : 1;
  // 获取请求的具体数据  变量解构赋值
  const { username, carPrice, carColor } = req.body;
  var date = new Date();
  var time = date.toLocaleString();
  // 创建一个新对象接收请求数据
  const newCar = {
    id: id,
    username,
    carPrice,
    carColor,
    创建时间: time,
    更新时间: time,
  };
  // 数据添加到储存位置
  data.car.push(newCar);
  // 数据储存到文件里面
  let result = await file.setFileData("../data621.json", data);
  // 判断是否添加成功
  if (result) {
    res.json({
      code: 200,
      message: "添加成功",
      data: newCar,
    });
  } else {
    res.json({
      code: 500,
      message: "fail",
    });
  }
});
// 删除
router.delete(
  `/delete/car/:id`,
  validateCarId,
  loadFileData,
  async (req, res) => {
    let id = req.params.id;
    // 筛选除了自己要删除的数据外的其他所有数据并返回接收
    let newCar = req.data.car.filter((car) => car.id != id);
    let newCars = req.data.car.filter((car) => car.id == id);
    req.data.car = newCar;
    // 储存到文件
    let result = await file.setFileData("../data621.json", req.data);
    // 判断是否删除成功
    if (result) {
      res.json({
        code: 200,
        message: "删除成功",
        data: newCars,
      });
    } else {
      res.json({
        code: 500,
        message: "fail",
      });
    }
  }
);
// 修改
router.put(`/put/car/:id`, loadFileData, validateCarId, async (req, res) => {
  let id = req.params.id;
  let car = req.data.car.find((car) => car.id == id);
  const { username, carPrice, carColor, 更新时间 } = req.body;
  var date = new Date();
  var time = date.toLocaleString();
  car.username = username;
  car.carPrice = carPrice;
  car.carColor = carColor;
  car.更新时间 = time;
  let result = await file.setFileData("../data621.json", req.data);
  if (result) {
    return res.send({
      code: 200,
      message: "修改成功",
      data: car,
    });
  } else {
    res.json({
      code: 500,
      message: "fail",
    });
  }
});
// 搜索
router.get("/get/cars/:id", loadFileData, validateCarId, async (req, res) => {
  let id = req.params.id;
  let car = req.data.car.filter((car) => car.id == id);
  var da = { car: car };
  let result = await file.setFileData("./data621.json", da);
  console.log(car);
  return res.json({
    code: 200,
    message: "搜索成功",
    data: car,
  });
  if (result) {
    return res.json({
      code: 200,
      message: "success",
    });
  } else {
    return res.json({
      code: 500,
      message: "fail",
    });
  }
});
module.exports = router;
